import React, { Component } from 'react';
// 导入样式
import './Login.scss'
// 导入登录api
import { user_login } from '../utils/api';

class Login extends Component {
    constructor(props){
        super(props)
        this.state={
            formData: {
                phone: '',
                pass: ''
            }
        }
    }
    componentDidMount(){
        user_login({ phone: '13611129070', pass: '1234' }).then((res) => {
            console.log(res.data);
        })
    }
    render() {
        return (
            <div class="login">
                <div class="title">登陆页</div>
                <div class="block">
                    <input type="text" v-model="formData.phone" placeholder="输入手机号"/>
                </div>
                <div class="block">
                    <input type="password" v-model="formData.pass" placeholder="输入密码"/>
                </div>
                <div class="block">
                    <input type="button" value="登陆" onClick={()=>{
                        this.login()
                    }} />
                </div>
            </div>
        );
    }

    login(){
        if (/^1[3-9]\d{9}$/.test(this.formData.phone) == false) {
            alert('请输入合法的手机号');
        } else if (!this.formData.pass) {
            alert('请输入密码')
        } else { //验证通过 
            //发起登陆请求
            user_login(this.formData).then((res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    //保存用户信息,token
                    localStorage.setItem('token', res.data.token);
                    localStorage.setItem('userinfo', JSON.stringify(res.data.userinfo));
                    //自动跳转到首页
                    // this.$router.push('/');
                } else {
                    alert('登陆失败!');
                }
            })
        }
    }
}

export default Login;